<template>
  <div class="chat-sidebar-warp" :class="{ 'expand': isExpand }">
    <ChatSidebarHeader @new-chat="startNewChat" @expand="handleExpand" />
    <ConversationList v-if="!isExpand" :conversList="conversationList" :pinnedList="pinnedList"
      :activeChatId="activeConversationId" @select="selectChat" @pin="handlePin" @edit="editNameSuccess"
      @delete="handleDelete" />
    <ChatSidebarFooter v-if="!isExpand" />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, toRefs } from "vue";
import ConversationList from "./ConversationList.vue";
import ConversationAction from "./ConversationAction.vue";
import ChatSidebarHeader from "./ChatSidebarHeader.vue";
import ChatSidebarFooter from "./ChatSidebarFooter.vue";
import { getConversationsList, conversationDelete } from "@/api/chat";
const { proxy } = getCurrentInstance()
const router = useRouter();
const props = defineProps({
  activeChatId: {
    type: [String, Number],
    default: null,
  },
});

const emit = defineEmits(["select", "new-chat", "expand"]);

// 模拟聊天列表数据
const conversationList = ref([]);
const activeConversationId = ref(null);
const loading = ref(false);
const isFished = ref(false);
const queryParams = reactive({
  limit: 100,
  pinned: false,
  page: 1,
});


const getList = async i => {
  // 获取列表
  if (i) {
    loading.value = false;
    isFished.value = false;
    queryParams.page = 1;
  }
  if (loading.value || isFished.value) return;
  loading.value = true;
  const res = await getConversationsList(queryParams);
  if (queryParams.page == 1) {
    conversationList.value = res.data;
  } else {
    conversationList.value = [...conversationList.value, ...res.data];
  }
  loading.value = false;
  isFished.value = res.data.length < queryParams.limit;
};

const pinnedList = ref([]);
const getPinnedList = async () => {
  try {
    const res = await getConversationsList({
      limit: 100,
      pinned: true,
    });
    pinnedList.value = res.data || [];
  } catch (error) {
    router.push('/login');
  }
}

const handleScroll = async () => {
  queryParams.page++;
  getList();
};

/** 监听选中的对话 */
const { activeChatId } = toRefs(props);
watch(activeChatId, async (newValue, oldValue) => {
  activeConversationId.value = newValue;
});

// 处理选中的对话
const selectChat = item => {
  if (!item.id) {
    return;
  }
  activeConversationId.value = item.id;
  emit("select", item);
  window['localStorage'].setItem('conversationID', item.id)
};

// 开启新对话
const startNewChat = () => {
  const tempConversation = conversationList.value.find(chat =>
    chat && chat.id.startsWith('temp_')
  );
  window['localStorage'].removeItem('conversationID');
  if (tempConversation) {
    activeConversationId.value = tempConversation.id;
    emit("select", tempConversation);
    return;
  }

  // 生成唯一ID，使用时间戳+随机数
  const uniqueId = `temp_${Date.now()}`;
  let obj = {
    id: uniqueId,
    name: '新的对话',
    created_at: Date.now(),
  }
  conversationList.value = [obj, ...conversationList.value];
  activeConversationId.value = uniqueId;
  emit("select", obj);
  emit("new-chat");
};

/** 初始化 */
const init = async () => {
  const conversationID = window['localStorage'].getItem('conversationID') || null;
  let arryList = [...conversationList.value, ...pinnedList.value];
  if (conversationID && !conversationID.startsWith('temp_')) {
    activeConversationId.value = conversationID;
    let item = arryList.find(item => item.id == activeConversationId.value);
    if (item) {
      await emit("select", item);
    } else {
      await emit("select", null);
    }
  } else {
    // 默认选中
    if (props.activeChatId && !props.activeChatId.startsWith('temp_')) {
      activeConversationId.value = props.activeChatId;
    } else {
      // 首次默认选中第一个
      if (arryList.length) {
        activeConversationId.value = arryList[0].id;
        await emit("select", arryList[0]);
      } else {
        await emit("select", null);
      }
    }
  }
};
const handlePin = (item) => {
  initData();
}


const editNameSuccess = response => {
  if (response?.id) {
    let item = conversationList.value.find(item => item.id == response.id);
    if (item) {
      item.name = response.name;
    }
  }
}
const handleDelete = async (item) => {
  await getPinnedList()
  await getList(1);
  if (item.id == activeConversationId.value) {
    window['localStorage'].removeItem('conversationID');
    let arryList = [...conversationList.value, ...pinnedList.value];
    if (arryList.length) {
      activeConversationId.value = arryList[0].id;
      await emit("select", arryList[0]);
    } else {
      activeConversationId.value = null;
      await emit("select", null);
    }
  }
  await init();
}
const initData = async () => {
  await getPinnedList()
  await getList(1);
  await init();
}

const upData = async () => {
  await getList(1);
  const conversationID = window['localStorage'].getItem('conversationID') || null;
  activeConversationId.value = conversationID;
}

/** 处理展开 */
const isExpand = ref(false);
const handleExpand = (expand) => {
  isExpand.value = expand;
  emit("expand", expand);
}



onMounted(async () => {
  initData()
});

defineExpose({ upData });
</script>

<style lang="scss" scoped>
.chat-sidebar-warp {
  transition: all 0.3s;

  &.expand {
    width: 0px;
    padding: 0;
    left: -300px;
  }

  position: relative;
  left: 0;
  overflow: hidden;
  width: 260px;
  flex-shrink: 0;
  background: #F6F7F9;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px;
  font-size: 14px;

  .sidebar-title {
    font-weight: 600;
    padding: 4px 0;
  }
}



// 滚动条样式
.chat-sidebar-warp .sidebar-content::-webkit-scrollbar {
  width: 6px;
}

.chat-sidebar-warp .sidebar-content::-webkit-scrollbar-thumb {
  background: #d9d9d9;
  border-radius: 3px;
}

.chat-sidebar-warp .sidebar-content::-webkit-scrollbar-track {
  background: #f0f0f0;
}
</style>
